package com.googlecode.cswish.struts;

import org.apache.commons.lang.math.NumberUtils;

import com.googlecode.cswish.struts.hibernate.ISite;

/**
 * 
 * Context holder to store the site & product information
 * 
 * TIPS:
 * 	use LogicalConnectionImpl.getConnection to trace the real connection
 * 
 * @author Jerry
 *
 */
public class ContextHolder {
	
	private static ThreadLocal<ContextHolder> contextHolder = new ThreadLocal<ContextHolder>();
	
	private String siteName = ISite.DEFAULT_NAME;
	
	private String productName;
	
	private String dbName;
	
	private ClassLoader oldClassLoader;
	
	private ContextHolder() {
	}
	
	public static ContextHolder get() {
		ContextHolder context = contextHolder.get();
		if (context == null) {
			// only create once, initialize it at StrutsExecuteFilter
			context = new ContextHolder();
			contextHolder.set(context);
		}
		return context;
	}

	public String getSiteName() {
		return siteName;
	}

	public void setSiteName(String siteName) {
		this.siteName = siteName;
		if (NumberUtils.isNumber(siteName)){
			sid = Integer.parseInt(siteName);
		}
//		if (siteName != null && !"saas".equals(siteName)){
//			sid = Integer.valueOf(siteName);
//		}
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}
	
	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	public ClassLoader getOldClassLoader() {
		return oldClassLoader;
	}

	public void setOldClassLoader(ClassLoader oldClassLoader) {
		this.oldClassLoader = oldClassLoader;
	}

	public void reset() {
		this.dbName = null;
		this.sid = null;
		this.siteName = ISite.DEFAULT_NAME;
		this.productName = null;
		this.oldClassLoader = null;
	}

	private Integer sid;
	public Integer getSid() {
		return sid;
	}
}
